package cn.liutao.upload.api;

import cn.hutool.core.net.multipart.MultipartFormData;
import cn.hutool.core.net.multipart.UploadFile;
import cn.hutool.extra.servlet.ServletUtil;
import cn.liutao.common.exception.OrderException;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author: liutao
 * @description: 通用文件上传
 * @date: 2023/11/23 22:18
 */
@Slf4j
public abstract class UploadServlet extends HttpServlet {
    protected UploadService uploadService;
    protected String url;//保存文件上传的路径
    /**
     * 定义一个默认的设置文件上传的方法
     * @return 返回文件上传地址
     */
    public String getUploadPath(String path){
        return path;
    }
    @Override
    public void init() throws ServletException {
        uploadService = UploadService.getInstance();
    }
    /**
     * 通用上传接口
     * @param req request
     * @param resp response
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
        if (!ServletUtil.isMultipart(req)) {
            throw new OrderException("请使用文件上传");
        }
        MultipartFormData multipart = ServletUtil.getMultipart(req);
        UploadFile file = multipart.getFile("file");
        String path = multipart.getParam("path");
        try {
            String suffix = uploadService.getExtension(file.getFileName());
            File tempFile = File.createTempFile("upload", ".".concat(suffix));
            file.write(tempFile);
            //具体文件执行逻辑
            String uploadPath = getUploadPath(path);
            //上传文件
            url = uploadService.upload(tempFile, uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传文件发生错误：{}",e.getMessage());
            ServletUtils.error(resp,"文件上传失败");
            return;
        }
        ServletUtils.ok(resp,url,"上传成功");
        log.info("文件上传成功,URL:{}",url);
    }
}
